using System.IO;
using System.Reflection;

namespace CppWrapper.GeneratorService
{
  internal class DependentFilesWriter
  {
    const string prefix = "CppWrapper.GeneratorService.DependentSources.";

    public static void CopyDependentFilesToOutputDirectory(string targetDirectory)
    {
      Assembly assembly = Assembly.GetExecutingAssembly();
      foreach (string resourceName in assembly.GetManifestResourceNames())
      {
        if (resourceName.StartsWith(prefix))
        {
          StreamReader dependentContentStream = new StreamReader(assembly.GetManifestResourceStream(resourceName));
          string fileName = resourceName.Remove(0, prefix.Length);
          string outFileName = Path.Combine(targetDirectory, fileName);
          FileInfo existingFileInfo = new FileInfo(outFileName);
          if (!existingFileInfo.Exists || !existingFileInfo.IsReadOnly)
          {
            using (StreamWriter fileStream = new StreamWriter(new FileStream(outFileName, FileMode.Create)))
            {
              while (!dependentContentStream.EndOfStream)
              {
                fileStream.Write(dependentContentStream.ReadToEnd());
              }
            }
          }
        }
      }
    }
  }
}
